# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 
# @Last Modified by: CPS
# @Last Modified time: 2021-04-12 03:27:20.556970
# @file_path "D:\CPS\IDE\JS_SublmieText\Data\Packages\CPS\core"
# @Filename "update_channel.py"
# @Description: 功能描述
#

import sublime
import sublime_plugin
import os
import time

from .core import utils
from .core import download_channel_by_git

PLUGIN_NAME = "testt_update_channel"
SETTING_FILE = "testt.sublime-settings"
FOLDER_LIST = {}
SETTINGS = {}

DEFAULT_CONTROL_FILE = { "channels":[], "create_by_testt":"update_channel.py" }

DEFAULT_SETTING_FILE = { PLUGIN_NAME:{} }


def get_floder_list() -> dict:
    return {
        "package_path":os.path.join(sublime.packages_path(),PLUGIN_NAME),
        'user_path':os.path.join(sublime.packages_path(),'User'),
        'channel_v3_file': os.path.join(sublime.packages_path(), PLUGIN_NAME, 'channel_v3.json'),
        'config_file':os.path.join(sublime.packages_path(), PLUGIN_NAME, '.config.json'),
        'default_settings':os.path.join(sublime.packages_path(), PLUGIN_NAME, '.sublime', SETTING_FILE),
        # 'user_settings':os.path.join(sublime.packages_path(),'User', SETTING_FILE),
        'package_settings':os.path.join(sublime.packages_path(),'User','Package Control.sublime-settings'),
    }

def plugin_loaded():
    print(f'{PLUGIN_NAME} 加载成功')
    global FOLDER_LIST
    FOLDER_LIST = get_floder_list()

    def plugin_loaded_async():
        global SETTINGS
        with open(FOLDER_LIST['default_settings'], 'r', encoding='utf8') as f:
            SETTINGS = sublime.decode_value(f.read()).get(PLUGIN_NAME, {})
            if len(list(SETTINGS.keys())) == 0:
                raise Exception('读取配置失败 ~~~ 请确保一下文件真实存在： ', FOLDER_LIST['default_settings'])

            # print('读取settings 1: ', SETTINGS.keys())

        _settings = sublime.load_settings(SETTING_FILE)
        utils.recursive_update(SETTINGS, _settings.to_dict()[PLUGIN_NAME])
        _settings.add_on_change(SETTING_FILE, _on_settings_change)

    def _on_settings_change() -> dict:
        global SETTINGS

        tmp = sublime.load_settings(SETTING_FILE).get(PLUGIN_NAME, False)
        
        if not tmp or not isinstance(tmp, dict): return

        utils.recursive_update(SETTINGS, tmp)

        print(f'{SETTING_FILE} 触发更新。')
        return SETTINGS
    
    # 在另一个进程执行该函数( 这样不会阻塞窗口的初始化，造成载入文件卡顿 )
    sublime.set_timeout_async(plugin_loaded_async)
    sublime.set_timeout_async(check_update)


def check_update():
    print('xxxxxxxxxxx> 执行 check_update()')
    global FOLDER_LIST, SETTINGS
    if not SETTINGS.get("auto_update", False): return

    currt_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

    # 获取
    with open(FOLDER_LIST["config_file"], 'r+', encoding='utf8') as f:
        config = sublime.decode_value(f.read())
        if config["update_last_time"] == "":
            # 写入当前时间，并更新一次
            print('首次写入更新时间 ->', currt_date)
            config["update_last_time"] = currt_date
            f.seek(0, 0)
            f.write(sublime.encode_value(config, pretty=True))

    update_last_time = config.get("update_last_time", currt_date)
    update_interval = SETTINGS.get("update_interval", 7) # 默认间隔7天更新一次

    # 对比时间是否已到
    if update_last_time == currt_date:
        print('当前时间相同')
        # 当最后更新时间跟当前时间相同，表示首次运行，执行一次更新
        # update()
        # return

    res = utils.time_compare_time(currt_date, update_last_time)

    print('两个日期对比结果： ', res)

    if res > update_interval:
        print('已超过，执行更新')
        update()
    else:
        print('不需要更新，')
    
def update():
    print('执行更新')
    global FOLDER_LIST
    currt_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    output = os.path.join(FOLDER_LIST['package_path'],'channelV3', f'channel_v3_{currt_time}')
    
    options = {}
    options["channel_v3_git_file"] = SETTINGS["channel_v3_git_file"]

    
    res = download_channel_by_git.run(output=output, options=options)
    print(res)
    pass


def update_channel_file():
    pass

class TesttUpdateChannelCommand(sublime_plugin.TextCommand):
    def run(self, view) -> None:
        global SETTINGS,FOLDER_LIST
        # 检查文件
        if not self.check_folder(): return

        # 将channel_v3_file路径写到配置文件
        channel_v3_file:str = FOLDER_LIST['channel_v3_file']
        currt_settings_file:str = FOLDER_LIST['package_settings']

        #读取现有配置文件
        with open(currt_settings_file,'r',encoding='utf8') as f:
            # currt_settings = json5.load(f)
            currt_settings = sublime.decode_value(f.read())

            # 如果当前配置不存在 channels 这个键，则创建
            if not currt_settings.get('channels'):
                currt_settings['channels'] = [channel_v3_file]

            else:
                #判断是否已存在需要添加的 channel
                if not channel_v3_file in currt_settings['channels']:
                    currt_settings['channels'].append(channel_v3_file)

        # 写入新文件
        with open(currt_settings_file,'w',encoding='utf8') as f:
            # json.dump(currt_settings, f, sort_keys=True, indent='  ',ensure_ascii=False)

            f.write(sublime.encode_value(currt_settings, pretty=True))

        print('更新文件成功')

    def check_folder(self) -> bool:
        res = True

        # 各个要验证的文件夹
        try:
            for key,each in get_floder_list().items():
                if not os.path.exists(each):
                    if key == "package_settings":
                        if self.create_Control_settings_file(each) : continue

                    # elif key == "user_settings":
                    #     continue
                    #     self.create_settings_file(each, DEFAULT_SETTING_FILE)

                    res = False
                    print(f'>>>>>> 缺少必要的文件 {each}, {key}')
                    raise FileNotFoundError

        except FileNotFoundError:
            res = False

        except Exception as e:
            print('未知错误', e)

        finally:
            return res

    def create_settings_file(sefl, file_name, data):
        try:
            with open(file_name, 'w', encoding='utf8') as f:
                f.write(sublime.encode_value(data, pretty=True))
                return True
        except Exception:
            return False

    # 创建空的Control.sublime-settings 文件
    def create_Control_settings_file(self, new_file:str) -> bool:
        try:
            with open(new_file,'w',encoding='utf8') as f:
                # json.dump(f, sort_keys=True,indent='  ',ensure_ascii=False)

                n = sublime.encode_value({ "channels":[], "create_by_testt":"update_channel.py" }, pretty=True )
                # tar = '''/*!\n'''
                # tar += ''' * @Create By : testt_update_channel.py\n'''
                # tar += ''' */\n\n'''
                # n = tar+n

                f.write(n)
                return True

        except Exception:
            return False
